package notify

import (
	"context"
	"nnxy-search-api/search-public-api/global/response"
	"strconv"

	"github.com/gin-gonic/gin"

	"nnxy-search-api/search-public-api/api"
	"nnxy-search-api/search-public-api/global"
	"nnxy-search-api/search-public-api/proto"
	"nnxy-search-api/search-public-api/validator/forms"
)

func New(ctx *gin.Context) {
	noticeForm := forms.NoticeForm{}
	err := ctx.ShouldBindJSON(&noticeForm)
	if err != nil {
		api.HandleValidatorError(err, ctx)
		return
	}
	_, err = global.PublicSrvClient.CreateNotice(context.Background(), &proto.NoticeRequest{
		Title:   noticeForm.Title,
		Content: noticeForm.Content,
		Sort:    noticeForm.Sort,
	})
	if err != nil {
		api.HandlerGrpcErrorToHttp(err, ctx)
		return
	}
	response.Success(ctx)
}
func List(ctx *gin.Context) {
	pageStr := ctx.DefaultQuery("page", "1")
	limitStr := ctx.DefaultQuery("limit", "10")
	page, _ := strconv.Atoi(pageStr)
	limit, _ := strconv.Atoi(limitStr)
	req := proto.NoticeRequest{
		Page:  int32(page),
		Limit: int32(limit),
	}
	if title := ctx.Query("title"); title != "" {
		req.Title = title
	}
	rsp, err := global.PublicSrvClient.GetNoticeList(context.Background(), &req)
	if err != nil {
		api.HandlerGrpcErrorToHttp(err, ctx)
		return
	}
	result := map[string]interface{}{
		"total": rsp.Total,
	}

	data := make([]map[string]interface{}, 0)
	for _, notice := range rsp.Data {
		data = append(data, conventNoticeToRsp(notice))
	}
	result["data"] = data
	response.SuccessData(ctx, result)
}

func Detail(ctx *gin.Context) {
	id, _ := strconv.Atoi(ctx.Param("id"))
	req := proto.NoticeRequest{
		Id: int64(id),
	}
	rsp, err := global.PublicSrvClient.GetNoticeInfoById(context.Background(), &req)
	if err != nil {
		api.HandlerGrpcErrorToHttp(err, ctx)
		return
	}
	response.SuccessData(ctx, conventNoticeToRsp(rsp))
}

func Update(ctx *gin.Context) {
	id, _ := strconv.Atoi(ctx.Param("id"))
	noticeForm := forms.NoticeForm{}
	err := ctx.ShouldBindJSON(&noticeForm)
	if err != nil {
		api.HandleValidatorError(err, ctx)
		return
	}
	_, err = global.PublicSrvClient.UpdateNotice(context.Background(), &proto.NoticeRequest{
		Id:      int64(id),
		Title:   noticeForm.Title,
		Content: noticeForm.Content,
		Sort:    noticeForm.Sort,
	})
	if err != nil {
		api.HandlerGrpcErrorToHttp(err, ctx)
		return
	}
	response.Success(ctx)
}

func Delete(ctx *gin.Context) {
	id, _ := strconv.Atoi(ctx.Param("id"))
	req := proto.NoticeRequest{
		Id: int64(id),
	}
	_, err := global.PublicSrvClient.DeleteNotice(context.Background(), &req)
	if err != nil {
		api.HandlerGrpcErrorToHttp(err, ctx)
		return
	}
	response.SuccessMsg(ctx, "删除成功")
}

func conventNoticeToRsp(notice *proto.NoticeInfoRsp) map[string]interface{} {
	item := map[string]interface{}{
		"id":      notice.Id,
		"title":   notice.Title,
		"status":  notice.Status,
		"sort":    notice.Sort,
		"Content": notice.Content,
	}
	return item
}
